import { defineStore } from "pinia";
import {
  createInforNews,
  deleteInforNews,
  fetchAllInforNews,
  updateInforNews,
  fetchInforNewsDetail,
} from "@/api/inforemation/news";
import type { IInforNews } from "@/api/inforemation/news";
import { ref } from "vue";

export const useInforNewsStore = defineStore("inforNews", () => {
  const newsList = ref<IInforNews[]>([]);
  const loading = ref(false);
  const error = ref<string | null>(null);

  // 获取所有医疗新闻
  const getAllNews = async () => {
    try {
      loading.value = true;
      error.value = null;
      const res = await fetchAllInforNews();
      newsList.value = res.data;
      return res.data;
    } catch (err) {
      error.value = "获取医疗新闻列表失败";
      console.error("获取医疗新闻列表失败:", err);
      throw err;
    } finally {
      loading.value = false;
    }
  };

  // 新增医疗新闻
  const addNews = async (data: IInforNews) => {
    try {
      loading.value = true;
      await createInforNews(data);
      await getAllNews();
    } catch (err) {
      console.error("新增医疗新闻失败:", err);
      throw err;
    } finally {
      loading.value = false;
    }
  };

  // 更新医疗新闻
  const editNews = async (data: IInforNews) => {
    try {
      loading.value = true;
      await updateInforNews(data);
      await getAllNews();
    } catch (err) {
      console.error("更新医疗新闻失败:", err);
      throw err;
    } finally {
      loading.value = false;
    }
  };

  // 删除医疗新闻
  const removeNews = async (id: number | string) => {
    try {
      loading.value = true;
      await deleteInforNews(id);
      await getAllNews();
    } catch (err) {
      console.error("删除医疗新闻失败:", err);
      throw err;
    } finally {
      loading.value = false;
    }
  };

  //根据id获取新闻
  const getNewsById = async (id: number | string) => {
    try {
      loading.value = true;
      const res = await fetchInforNewsDetail(id);
      return res.data;
    } catch (err) {
      error.value = "获取医疗新闻列表失败";
      console.error("获取医疗新闻列表失败:", err);
      throw err;
    }
  };


  return {
    newsList,
    loading,
    error,
    getAllNews,
    addNews,
    editNews,
    removeNews,
    getNewsById,
  };
});